/**
 * 定时任务管理器
 * @author yanwl 
 * @date 2014-11-20
 */
package com.chnbst.bstyun.task;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.chnbst.bstyun.core.common.DateUtil;
import com.chnbst.bstyun.core.common.ReadProperties;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.core.common.email.EmailUtil;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Email;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.GoodsRelation;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Payment;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.service.EmailService;
import com.chnbst.bstyun.service.GoodsRelationService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PaymentService;
import com.chnbst.bstyun.service.UserService;

@Component
public class Task {
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private ReadProperties read;
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private EmailService emailService;
	@Autowired
	private Eos eos;
	@Autowired
	private GoodsRelationService goodsRelationService;
	
	/*订单到期账户停用*/
	@Scheduled(cron = "0 0 0 * * ?")
	public void sendExtendRenewRemind() throws Exception { 
		//延长续费通知邮件
		Email email = emailService.selectEmail(42);
		
		//正好达到到期时间
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sortField", "pay_time");
		map.put("sortOrder", "desc");
		map.put("groupField", "t.user_id,t.goods_id");
		map.put("doType", 0);
		List<OrderVo> orders = orderService.selectTimeOutOrderVo(map);
		
		//位于到期时间和延长到期时间之间
		map.put("doType", 1);
		map.put("day", email.getTimeSpace());
		List<OrderVo> orders1 = orderService.selectTimeOutOrderVo(map);
		
		for (OrderVo order : orders) {
			String proMealName = order.getGoodsName();
			String dayStr = String.valueOf(email.getTimeSpace());
			List<GoodsRelation> goodsRelations = goodsRelationService.selectByGoodsId(order.getGoodsId());
			String appCode = "";
			for (GoodsRelation goodsRelation : goodsRelations) {
				appCode += goodsRelation.getProductNum()+",";
			}
			Integer userId = order.getUserId();
			User user = userService.selectUserInfoByUserId(userId);
			String domainStr = user.getCompanyDomainName();
			
			Integer orderId = order.getOrderId();
			String url = read.getBstyunUrl()+"/myservice/order/toRenewPage?orderId="+orderId;
			String a = "<a href='"+url+"'>续费</a>";
			
	    	String content = email.getEmailContent();
	    	content = content.replace("arg0", user.getUserEmail()).replace("arg1", proMealName).
	    			replace("arg2", dayStr).replace("arg3", a);
	    	EmailUtil.sendMail(user.getPersonEmail(), email.getEmailSubject(), content+email.getEmailSign());
			
			Integer parentId = order.getParentId();
			if(parentId != userId){
				User registerUser = userService.selectUserInfoByUserId(parentId);
				String userInfoName = registerUser.getUserEmail();
				if(SignUtil.isNotEmpty(registerUser.getUserEmail())) {
					content = content.replace("arg0", userInfoName);
					EmailUtil.sendMail(userInfoName, email.getEmailSubject(), content+email.getEmailSign());
				}
			}
			//调用停用某个应用接口
			eos.doProduct(domainStr, false, appCode, proMealName);
		}
		
		
		for (OrderVo order : orders1) {
			String proMealName = order.getGoodsName();
			List<GoodsRelation> goodsRelations = goodsRelationService.selectByGoodsId(order.getGoodsId());
			String appCode = "";
			for (GoodsRelation goodsRelation : goodsRelations) {
				appCode += goodsRelation.getProductNum()+",";
			}
			Integer userId = order.getUserId();
			User user = userService.selectUserInfoByUserId(userId);
			String domainStr = user.getCompanyDomainName();
			
			//调用停用某个应用接口
			eos.doProduct(domainStr, false, appCode, proMealName);
		}
	}
	
	/*续费提醒*/
	@Scheduled(cron = "0 0 1 * * ?")
	public void sendRenewRemind() throws ParseException { 
		//某天后的日期
		Email email = emailService.selectEmail(35);
		Date overTime = SignUtil.getOvertime(5, +email.getTimeSpace(), new Date());
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", null);
		map.put("overTime", overTime);
		map.put("doType", 0);
		map.put("sortField", "pay_time");
		map.put("sortOrder", "desc");
		map.put("groupField", "t.user_id,t.goods_id");
		List<OrderVo> orders = orderService.selectLastOrdersByUserId(map);
		
		for (OrderVo order : orders) {
			String proMealName = order.getGoodsName();
			Date proOverTime = order.getOverTime();
			String overTimeStr = SignUtil.time2str(proOverTime, "yyyy-MM-dd HH:mm");
			String dayStr = DateUtil.getMonth("getOverTime", new Date(), proOverTime);
			if(SignUtil.isEmpty(dayStr)) {
				dayStr = "1天";
			}
			String dateStr = dayStr+"后（"+overTimeStr+"）";
			Integer orderId = order.getOrderId();
			String url = read.getBstyunUrl()+"/myservice/order/toRenewPage?orderId="+orderId;
			String a = "<a href='"+url+"'>续费</a>";
			Integer userId = order.getUserId();
			User user = userService.selectUserInfoByUserId(userId);
			
	    	String content = email.getEmailContent();
	    	content = content.replace("arg0", user.getUserEmail()).replace("arg1", proMealName).
	    			replace("arg2", dateStr).replace("arg3", a);
	    	EmailUtil.sendMail(user.getPersonEmail(), email.getEmailSubject(), content+email.getEmailSign());
			
			Integer parentId = order.getParentId();
			if(parentId != userId){
				User registerUser = userService.selectUserInfoByUserId(parentId);
				String userInfoName = registerUser.getUserEmail();
				if(SignUtil.isNotEmpty(registerUser.getUserEmail())) {
					content = content.replace("arg0", userInfoName);
					EmailUtil.sendMail(userInfoName, email.getEmailSubject(), content+email.getEmailSign());
				}
			}
		}
	} 
	
	
	/*删除达到延长续费时间的账户*/
	@Scheduled(cron = "0 0 2 * * ?") 
	public void deleteUsers() throws Exception { 
		//延长续费通知邮件
		Email email = emailService.selectEmail(42);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("day", email.getTimeSpace());
		map.put("sortField", "pay_time");
		map.put("sortOrder", "desc");
		map.put("groupField", "t.user_id,t.goods_id");
		map.put("doType", 2);
		List<OrderVo> orders = orderService.selectTimeOutOrderVo(map);
		
		for (OrderVo order : orders) {
			Integer userId = order.getUserId();
			User user = userService.selectUserInfoByUserId(userId);
			String domainStr = user.getCompanyDomainName();
			String proMealName = order.getGoodsName();
			Goods goods = goodsService.selectByGoodsId(order.getGoodsId());
			if("0".equals(goods.getGoodsRalateGoods())) {
				//调用退单接口,即删除全部protal用户
				eos.chargeBack(domainStr,proMealName,userId,0);
			}else {
				List<GoodsRelation> goodsRelations = goodsRelationService.selectByGoodsId(goods.getGoodsId());
				String appCode = goodsRelations.get(0).getProductNum();
				//调用删除使用某应用的用户接口
				eos.deleteUsers(domainStr,appCode, proMealName,userId);
			}
		}
	} 
	
	/*未付款的订单作废*/
	@Scheduled(fixedRate = 3600000) 
    public void closeNoPayOrder() { 
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderState", 0);
		map.put("userId", null);
		List<Order> orders = orderService.selectOrdersByMap(map);
		for (Order order : orders) {
			long closeTime = SignUtil.getOvertime(5, +7, order.getOccurTime()).getTime();
			long currTime = new Date().getTime();
			Goods goods = goodsService.selectByGoodsId(order.getGoodsId());
			if(closeTime < currTime) {
				if("0".equals(goods.getGoodsRalateGoods())) {
					if(order.getBuyType() == 0) {
						User user = userService.selectUserInfoByUserId(order.getUserId());
						if(user != null) {
							user.setUserValid("1");
							user.setIsLive("0");
							userService.updateUserByKey(user);
						}
					}
				}
				Payment payment = paymentService.selectPaymentByOrderId(order.getOrderId());
				if(payment != null) {
					payment.setIsCancel(1);
					paymentService.updatePayment(payment);
				}
				order.setOrderState(2);
				orderService.updateOrderByOrderId(order);
			}
		}
    } 
	
	/*到期后的订单在一定时间内订单作废，账户停用*/
	/*@Scheduled(cron = "0 0 0 * * ?") 
	public void closeTimeOutOrder() throws Exception { 
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderState", 1);
		map.put("userId", null);
		map.put("isFree", 1);
		List<Order> orders = orderService.selectOrdersByMap(map);
		for (Order order : orders) {
			long closeTime = SignUtil.getOvertime(5, +20, order.getOverTime()).getTime();
			long currTime = new Date().getTime();
			Goods goods = goodsService.selectByGoodsId(order.getGoodsId());
			if(closeTime < currTime) {
				if("0".equals(goods.getGoodsRalateGoods())) {
					Map<String, Object> map1 = new HashMap<String, Object>();
					map1.put("orderState", 1);
					map1.put("userId", order.getUserId());
					List<Order> list = orderService.selectOrdersByMap(map);
					if(list.size() < 2) {
						User user = userService.selectUserInfoByUserId(order.getUserId());
						if(user != null) {
							user.setUserValid("1");
							user.setIsLive("0");
							userService.updateUserByKey(user);
							user.setUserValid("1");
							boolean isSuccess =  userService.updateUser(user);
							if(isSuccess) {
								String restr = eos.doUser(user.getUserEmail(), false);
								if(!"ok".equalsIgnoreCase(restr)) {
									user.setUserValid("0");
									userService.updateUser(user);
									System.out.println("订单到期后的用户："+user.getUserEmail()+"停用失败");
								}
							}else {
								System.out.println("订单到期后的用户："+user.getUserEmail()+"停用失败");
							}
						}
					}
				}
				order.setOrderState(2);
				orderService.updateOrderByOrderId(order);
			}
		}
	} */
}
